<template>
  <div>
    <NavigationBar background-color="#fff" />
    <Message ref="message" />
    <Loading ref="loading" fullscreen />
    <SelectArea
      ref="selectArea"
      maskCloseAble
      v-model="openPicker"
      :defaultAreaCode="addressAdCode"
      @confirm="pickerConfirm" />

    <div class="address-container w-screen">
      <image
        class="bg-image fixed top-0 left-0 wh-full -z-1"
        src="" />
      <div class="title-container w-full h-180rpx px-50rpx pt-50rpx pb-30rpx">
        <div class="title-text inline text-54rpx font-bold text-black">
          {{ isNewAddress ? '新增地址' : '编辑地址' }}
        </div>
        <div
          class="delete-btn float-right mt-32rpx text-30rpx text-hex-555"
          v-show="!isNewAddress"
          @click="handleDeleteClick">
          <i class="far fa-trash-can mr-6rpx" />
          删除
        </div>
      </div>
      <div class="address-container w-full px-50rpx">
        <div class="address-form w-full">
          <div class="name-container w-full h-200rpx flex">
            <div class="name-left w-150rpx flex-column text-black">
              <view>联系人</view>
              <view></view>
            </div>
            <div class="name-right h-full flex-column">
              <div class="name-input-container w-full text-30rpx">
                <input
                  class="wh-full text-black"
                  type="text"
                  data-name="contactName"
                  v-model="contactName">
                <div
                  class="name-placeholder wh-full relative pointer-events-none text-hex-c0c0c0"
                  v-show="contactName === ''">
                  收货人姓名
                </div>
              </div>
              <div class="gender-container w-full flex">
                <div
                  class="gender-btn gender-btn--default"
                  data-name="gentleman"
                  :class="contactGender === 1 ? 'gender-btn--selected' : ''"
                  @click="handleGenderClick">
                  先生
                </div>
                <div
                  data-name="lady"
                  class="gender-btn gender-btn--default"
                  :class="contactGender === 2 ? 'gender-btn--selected' : ''"
                  @click="handleGenderClick">
                  女士
                </div>
              </div>
            </div>
          </div>
          <div class="phone-container w-full h-100rpx flex">
            <div class="phone-left w-150rpx h-full text-black">
              <view class="wh-full text-30rpx font-bold">电话</view>
            </div>
            <div class="phone-right h-full text-30rpx">
              <input
                class="wh-full text-black"
                type="number"
                data-name="contactPhone"
                v-model="contactPhone"
                maxlength="11">
              <div
                class="phone-placeholder wh-full relative pointer-events-none text-hex-c0c0c0"
                v-show="contactPhone === ''">
                联系手机号
              </div>
            </div>
          </div>
          <div class="area-container w-full h-100rpx flex">
            <div class="area-left w-150rpx h-full text-black">
              <view class="wh-full text-30rpx font-bold">地区</view>
            </div>
            <div class="area-right h-full text-30rpx overflow-hidden">
              <div
                class="input h-full text-black"
                @click="handleAreaClick">
                {{ addressArea[0] }} {{ addressArea[1] }} {{ addressArea[2] }}
              </div>
              <div
                class="area-placeholder h-full relative pointer-events-none text-hex-c0c0c0"
                :style="{opacity: `${addressArea[0] === '' ? 1 : 0 }`}">
                选择地区
              </div>
              <div
                class="picker-btn w-80rpx h-full flex-column justify-center float-right relative text-hex-555 text-center text-48rpx"
                @click="handleAreaClick">
                <i class="fas fa-angle-right" />
              </div>
            </div>
          </div>
          <div class="detail-container w-full h-100rpx flex">
            <div class="detail-left w-150rpx h-full text-black">
              <view class="wh-full text-30rpx font-bold">门牌号</view>
            </div>
            <div class="detail-right h-full text-30rpx">
              <input
                class="h-full text-black"
                type="text"
                data-name="addressDetail"
                v-model="addressDetail">
              <div
                class="detail-placeholder h-full relative pointer-events-none text-hex-c0c0c0"
                :style="{opacity: `${addressDetail === '' ? 1 :0}`}">
                例：中山五路98号301室
              </div>
              <div
                class="map-btn w-80rpx h-full  flex-column justify-center float-right relative text-hex-555 text-center text-42rpx"
                @click="handleMapBtnClick">
                <i class="fas fa-location-dot text-hex-999" />
              </div>
            </div>
          </div>
          <div class="set-default-container w-full h-120rpx mt-30rpx">
            <u-checkbox
              v-model="isDefaultAddress"
              name="defaultAddress"
              shape="circle"
              active-color="#f4756b"
              size="28"
              label-size="28">
              设为默认地址
            </u-checkbox>
          </div>
        </div>
        <div
          class="confirm-btn w-full h-94rpx text-36rpx text-center text-white font-bold bg-primary"
          @click="handleConfirm">
          保 存
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import Message from '@/components/message/src/message.vue'
  import {MessageMethod} from '@/components/message'
  import Loading from '@/components/loading/src/loading.vue'
  import {LoadingMethod} from '@/components/loading'
  import NavigationBar from '@/components/navigation-bar/src/navigation-bar.vue'
  import SelectArea from '@/components/select-popup/select-area/src/select-area.vue'
  import {SelectAreaMethod, SelectResult} from '@/components/select-popup/select-area'
  import {useSystemStore} from '@/store'
  import {addressApi} from '@/service/api'
  import {UserAddressParam} from '@/service/api/modules/address/param'

  const {navigationHeight} = storeToRefs(useSystemStore())

  const eventChannel = ref<any>(null) //页面事件通信
  const message = ref<InstanceType<typeof Message> & MessageMethod>(null)
  const loading = ref<InstanceType<typeof Loading> & LoadingMethod>(null)
  const selectArea = ref<InstanceType<typeof SelectArea> & SelectAreaMethod>(null)

  const isNewAddress = ref<boolean>(true) //是否为新增地址，为false时为编辑地址，用于改变标题内容
  const openPicker = ref<boolean>(false) //selectArea组件的双向绑定值，为true时打开Picker
  const addressId = ref<number | string | null>(null) //编辑地址时，当前地址的id
  const contactName = ref<string>('') //联系人姓名
  const contactGender = ref<0 | 1 | 2>(0) //联系人性别，[0: 未选择, 1: 先生, 2: 女士]
  const contactPhone = ref<string>('') //联系人手机号
  const addressArea = ref<Array<string>>(['', '', '']) //地区名称数组
  const addressAdCode = ref<Array<string>>(['44', '4401', '440103']) //行政编码数组，已绑定为selectArea组件的Picker初始值
  const addressDetail = ref<string>('') //门牌号（详细地址）
  const isDefaultAddress = ref<boolean>(false) //是否设为默认地址
  const isSelectMode = ref<boolean>(false) //是否为选择地址模式（用于下单页）

  // 地图按钮点击监听事件
  const handleMapBtnClick = (): void => {
    //跳转到amap页面，并接收回传数据
    uni.navigateTo({
      url: '/pagesBySystem/amap/amap',
      events: {
        position: (data: any) => {
          if (data) {
            addressAdCode.value = [data.resultDetails.adcode.slice(0, 2), data.resultDetails.adcode.slice(0, 4), data.resultDetails.adcode]
            addressDetail.value = `${data.resultDetails.address}${data.resultDetails.name}`
            let addressAreaTemp
            if ((addressAreaTemp = selectArea.value.queryAreaName(addressAdCode.value[2])) !== false) {
              //查询行政区域名称成功
              addressArea.value = addressAreaTemp
            } else {
              //查询失败
              openPicker.value = true
            }
          }
        }
      }
    })
  }

  // selectArea组件的Picker确认事件
  const pickerConfirm = (e: SelectResult): void => {
    addressArea.value = [e.province?.name, e.city?.name, e.area?.name] as string[]
    addressAdCode.value = [e.province?.code, e.city?.code, e.area?.code] as string[]
  }

  // 地区输入框点击事件
  const handleAreaClick = (): void => {
    // selectArea.value.init()
    openPicker.value = true
  }

  // 联系人性别点击事件
  const handleGenderClick = (e: Event): void => {
    const gender = (e.currentTarget as HTMLElement).dataset.name
    if (gender === 'gentleman') {
      contactGender.value = 1
    } else if (gender === 'lady') {
      contactGender.value = 2
    }
  }

  // 删除按钮点击事件
  const handleDeleteClick = (): void => {
    uni.showActionSheet({
      alertText: '删除地址后将无法恢复',
      itemList: ['确定删除'],
      itemColor: '#f35b56',
      success: res => {
        if (res.tapIndex === 0 && !isNaN(Number(addressId.value))) {
          //确定删除地址
          addressApi.deleteOneAddress({
            addressId: addressId.value as number
          }).then(() => {
            loading.value.stopLoading()
            uni.navigateBack()
          }).catch(err => {
            loading.value.stopLoading()
            message.value.error({text: '删除失败'})
            console.error(err)
          })
        }
      }
    })
  }

  // 保存按钮点击事件
  const handleConfirm = useThrottleFn((): void => {
    if (checkInfo()) {
      const newAddress = {
        contacts: `${contactName.value}${contactGender.value === 0 ? '' : (contactGender.value === 1 ? '{#先生}' : '{#女士}')}`,
        areaCode: addressAdCode.value[2],
        addressDetail: addressDetail.value,
        phone: contactPhone.value,
        isDefault: isDefaultAddress.value
      }
      isNewAddress.value ? postAddresses(1, newAddress) : postAddresses(2, newAddress)
    }
  }, 2000, false, true)

  /**
   * 检验地址表单内容是否符合要求
   * @return {boolean} 是否验证通过
   */
  const checkInfo = (): boolean => {
    if (contactName.value.replace(/\s*/g, '') === '') {
      message.value.warning({text: '联系人不能为空'})
      contactName.value = ''
      return false
    }
    if (contactPhone.value.replace(/\s*/g, '') === '') {
      message.value.warning({text: '手机号不能为空'})
      return false
    } else if (!/^(13\d|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18\d|19[0-35-9])\d{8}$/.test(contactPhone.value)) {
      message.value.warning({text: '手机号格式有误'})
      return false
    }
    if (addressDetail.value.replace(/\s*/g, '') === '') {
      message.value.warning({text: '门牌号不能为空'})
      return false
    }
    if (addressArea.value?.every(item => item === '')) {
      message.value.warning({text: '地区不能为空'})
      return false
    }
    return true
  }

  /**
   * 提交地址修改
   * @param mode 编辑模式，[1: 新增地址, 2: 修改地址]
   * @param newAddress 地址信息
   */
  const postAddresses = (mode: 1 | 2, newAddress: UserAddressParam): void => {
    if (mode === 1) {
      //新增地址
      addressApi.addUserAddress({
        contacts: newAddress.contacts,
        phone: newAddress.phone,
        areaCode: newAddress.areaCode,
        addressDetail: newAddress.addressDetail,
        isDefault: newAddress.isDefault
      }).then(() => {
        if (isSelectMode.value) {
          //当前为选择地址模式
          eventChannel.value.emit('acceptDataFromOpenedPage', {
            address: newAddress
          })
        }
        uni.navigateBack()
      }).catch(err => {
        message.value.error({text: '保存失败'})
        console.error(err)
      })
    } else {
      //修改地址
      addressApi.updateUserAddress({
        id: addressId.value as number,
        contacts: newAddress.contacts,
        phone: newAddress.phone,
        areaCode: newAddress.areaCode,
        addressDetail: newAddress.addressDetail,
        isDefault: newAddress.isDefault
      }).then(() => {
        uni.navigateBack()
      }).catch(err => {
        message.value.error({text: '保存失败'})
        console.error(err)
      })
    }
  }

  onLoad(() => {
    try {
      //@ts-ignore
      eventChannel.value = getCurrentInstance().proxy.getOpenerEventChannel()
      eventChannel.value.on('editAddress', (data: any) => {
        isNewAddress.value = false
        addressId.value = data.data.id
        contactName.value = data.data.contactName
        contactGender.value = data.data.contactGender
        contactPhone.value = data.data.contactPhone
        addressAdCode.value = [data.data.areaCode.slice(0, 2), data.data.areaCode.slice(0, 4), data.data.areaCode]
        addressDetail.value = data.data.addressDetail
        addressArea.value = [data.data.areaName[0], data.data.areaName[1], data.data.areaName[2]]
        isDefaultAddress.value = data.data.isDefaultAddress
      })
      try {
        //@ts-ignore
        eventChannel.value = getCurrentInstance().proxy.getOpenerEventChannel()
        eventChannel.value.on('selectAddress', (data: any) => {
          isSelectMode.value = !!data.data
        })
      } catch (e) {
        isSelectMode.value = false
      }
    } catch (e) {
      isNewAddress.value = true
    }
  })

  onMounted(() => {
    selectArea.value.init()
  })
</script>

<style scoped lang="scss">
  @import 'edit-address';
</style>
